<?php

namespace App\Models;

class Order extends Model
{
    protected $typeMap = [
        1 => '诊断订单',
        2 => '鉴定订单',
    ];

    protected $fillable = [
        'no', 'car_id', 'type', 'bespeak', 'total_amount', 'coupon_amount', 'pay_amount',
        'remark', 'paid_at', 'payment_method', 'payment_no', 'closed', 'agreement', 'extra',
    ];

    protected $casts = [
        'closed'    => 'boolean'
    ];

    protected $dates = [
        'paid_at',
    ];

    protected $appends = ['type_new'];

    // 定义订单类型
    public function getTypeNewAttribute()
    {
        return $this->typeMap[$this->type];
    }

    // 定义订单状态
    public function getStatusAttribute()
    {
        if($this->paid_at == null && $this->bespeak == 0){
            return '未支付';
        }
        if($this->paid_at == null && $this->bespeak == 1){
            return '预约支付';
        }
        if($this->paid_at != null){
            return '交易完成';
        }
    }

    //
    protected static function boot()
    {
        parent::boot();
        // 监听模型创建事件，在写入数据库之前触发
        static::creating(function ($model) {
            // 如果模型的 no 字段为空
            if (!$model->no) {
                // 调用 findAvailableSn 生成订单流水号
                $model->no = static::findAvailableSn();
                // 如果生成失败，则终止创建订单
                if (!$model->no) {
                    return false;
                }
            }
        });
    }

    public function user()
    {
        return $this->belongsTo(User::class, "user_id", "id");
    }

    public function items()
    {
        return $this->hasOne(OrderItem::class, "order_id", "id");
    }


    // 订单流水号规则
    public static function findAvailableSn()
    {
        // 订单流水号前缀
        $prefix = 'C' . date('YmdHis');
        for ($i = 0; $i < 10; $i++) {
            // 随机生成 6 位的数字
            $no = $prefix . str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
            // 判断是否已经存在
            if (!static::query()->where('no', $no)->exists()) {
                return $no;
            }
        }
        return false;
    }


}
